package vsa.migrations.junit.envreader;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.logging.Logger;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.eclipse.emf.common.util.URI;
import org.emftext.language.java.JavaClasspath;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

/**
 * reads project layout from .project file
 * @author OleyMa
 *
 */
public class EnvReaderDotProject implements EnvReader {
	
	private static Logger LOGGER = Logger.getLogger(EnvReaderDotProject.class.getName());
	
	
	/**
	 * creates the java classpath from enviroment 
	 * @param javaClasspath
	 * @param projectPath
	 */
	public void readEnvironment (final JavaClasspath javaClasspath, final File projectPath) {
		
		File classpathFile = new File (projectPath.getAbsoluteFile(), ".classpath");
		if (! classpathFile.exists())
			throw new IllegalStateException("You need a .classpath file for migrating project <" + classpathFile.getAbsolutePath() + "> to junit4");

		DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
		DocumentBuilder dBuilder;
		Document doc;
		try {
			dBuilder = dbFactory.newDocumentBuilder();
			doc = dBuilder.parse(classpathFile);
		} catch (ParserConfigurationException e) {
			throw new RuntimeException(e);
		} catch (SAXException e) {
			throw new RuntimeException(e);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
		
		doc.getDocumentElement().normalize();

		NodeList elementsByTagName = doc.getElementsByTagName("classpathentry");

		for (int temp = 0; temp < elementsByTagName.getLength(); temp++) {

			   Node nNode = elementsByTagName.item(temp);
			   if (nNode.getNodeType() == Node.ELEMENT_NODE) {
			      Element eElement = (Element) nNode;
			      String kindElement = eElement.getAttribute("kind");
			      String pathElement = eElement.getAttribute("path");
			      String outputElement = eElement.getAttribute("output");
			      
			      if (kindElement.equals("src")) {
			    	  File filePath = new File (outputElement);
			    	  javaClasspath.registerSourceOrClassFileFolder(URI.createFileURI(filePath.getAbsolutePath()));
			    	  
			      }
			      else if (kindElement.equals("lib")) {
			    	  File filePath = new File (pathElement);
			    	  URI uri = URI.createFileURI(filePath.getAbsolutePath());
			    	  if (filePath.isFile() && filePath.getName().endsWith(".jar")) {
  		    		    LOGGER.info("register jarfile " + uri);
			    		javaClasspath.registerClassifierJar(uri);
			    	  }
			    	  else {
			    		LOGGER.info("register sourcefolder " + uri);
			    		javaClasspath.registerSourceOrClassFileFolder(uri);
			    	  }
			      }
			   }
		}
	}

}
